package com.wzh.yebServe.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.yebServe.mapper.EmployeeMapper;
import com.wzh.yebServe.mapper.MailLogMapper;
import com.wzh.yebServe.pojo.*;
import com.wzh.yebServe.service.*;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author wzh
 * @create 2022/11/19 19:33
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    private final EmployeeMapper employeeMapper;

    private final RabbitTemplate rabbitTemplate;

    private final MailLogMapper mailLogMapper;


    private final INationService iNationService;

    private final IPoliticsStatusService iPoliticsStatusService;

    private final IJobLevelService iJobLevelService;

    private final IPositionService iPositionService;

    private final IDepartmentService iDepartmentService;


    @Override
public RespPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
    //开启分页
    Page<Employee> page = new Page<>(currentPage, size);
    IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
    return new RespPageBean(employeeByPage.getTotal(), employeeByPage.getRecords());
}


    @Override
    public ResultBean maxWorkId() {
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workId)"));
     return ResultBean.success(null,String.format("%08d",Integer.parseInt(maps.get(0).get("max(workId)").toString())+1));
    }

    @Override
    public ResultBean addEmp(Employee employee) {
       //处理合同期限，保留2位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat=new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365)));
        boolean save = save(employee);
        if (save){
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);
            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(emp.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);
//            发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(msgId));
            return ResultBean.success("添加成功");
        }
        return ResultBean.error("添加失败");
    }

    @Override
    public ResultBean updateEmployee(Employee employee) {
        boolean b = updateById(employee);
        if (b){
            return ResultBean.success("更新成功");
        }
        return ResultBean.error("更新失败");
    }

    @Override
    public ResultBean deleteEmployee(Integer id) {
        boolean b = removeById(id);
        if (b){
            return ResultBean.success("删除成功");
        }
        return ResultBean.error("删除失败");
    }

    @Override
    public List<Employee> getEmployee(Integer id) {

        return  employeeMapper.getEmployee(id);
    }

    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
//        开启分页
        Page<Employee> page=new Page<>(currentPage,size);
        IPage<Employee> employeeIpage=employeeMapper.getEmployeeWithSalary(page);
        RespPageBean respPageBean=new RespPageBean(employeeIpage.getTotal(),employeeIpage.getRecords());
        return respPageBean;
    }



    @Override
    public void exportEmp(HttpServletResponse response) throws IOException {
        List<Employee> list=this.getEmployee(null);
//       导出参数 文件名 xxxx 导出的类型
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out=null;
        try {
            out =response.getOutputStream();
//            设置响应头的信息
            response.setHeader("content-type","application/octet-stream");
//            防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            sheets.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out!=null){
                out.close();
            }
        }

    }

    @Override
    public ResultBean importEmp(MultipartFile file) {
        ImportParams params=new ImportParams();
        List<Nation> nationList = iNationService.list();
        List<Position> positionList = iPositionService.list();
        List<Department> departmentList = iDepartmentService.list();
        List<JobLevel> jobLevelList = iJobLevelService.list();
        List<PoliticsStatus> politicsStatusList = iPoliticsStatusService.list();
//       去掉标题行
        params.setTitleRows(1);
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {
//               名族
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
//               部门
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
//               政治面貌
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
//               职位
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
//               职称
                employee.setJobLevelId(jobLevelList.get(jobLevelList.indexOf(new JobLevel(employee.getJobLevel().getName()))).getId());
            });
            if (this.saveBatch(list)){
                return ResultBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBean.error("导入失败");
    }
    }
